<?php
namespace hema\delivery\engine;

use app\common\model\Setting;

/**
 * UU配送
*/
class Uu extends Basics
{
	private $callback_url = 'task/delivery/uu';	//订单状态回调
	
    /**
     * 构造函数
    */
    public function __construct($order){
		$config = Setting::getItem('webdelivery',0)['uu'];
		parent::__construct($config, $order);
    }

	/**
     * 预发布订单 - 计算订单价格
	*/
	public function preOrder()
	{
		$order = $this->order;
		$user = $order['address'];//收货人信息
		$user_location = explode(',',$user['location']);//拆分收货人定位经纬度
		$shop = $order['shop'];//发货门店
		$shop_location = explode(',',$shop['coordinate']);//拆分门店定位经纬度
		$post_data = [
			'origin_id' => $order['order_id'],//第三方对接平台订单id
			'from_address' => $shop['address'],//起始地址
			//'from_usernote' => '',//起始地址具体门牌号(可为空)
			'to_address' => $user['detail'],//目的地址
			//'to_usernote' => '',//目的地址具体门牌号(可为空)
			'city_name' => $shop['city'],//订单所在城市名 称(如郑州市就填”郑州市“，必须带上“市”)
			'county_name' => $shop['district'],//订单所在县级地名称(如金水区就填“金水区”)(可为空)
			'subscribe_type' => '0',//预约类型 0实时订单 1预约取件时间(可为空)
			//'subscribe_time' => '',//预约时间（如：2015-06-18 12:00:00）没有可以传空字符串(可为空)
			'send_type' => '0',//订单小类 0帮我送(默认) 1帮我买
			'to_lat' => $user_location[0],//目的地坐标纬度，如果无，传0(坐标系为百度地图坐标系)
			'to_lng' => $user_location[1],//目的地坐标经度，如果无，传0(坐标系为百度地图坐标系)
			'from_lat' => $shop_location[0],//起始地坐标纬度，如果无，传0(坐标系为百度地图坐标系)
			'from_lng' => $shop_location[1] //起始地坐标经度，如果无，传0(坐标系为百度地图坐标系)
		];
		$result = $this->request_post('/v2_0/getorderprice.ashx',$post_data);
		if($result['return_code'] == 'ok'){
			return [
				'delivery_time' => '30分钟', //预计送达时间
				'delivery_distance' => $result['distance'] . '米', //配送距离
				'delivery_price' => '￥' . $result['need_paymoney'] . '元', //配送费用
				'uu' => $result
			];
		}
		$this->error = $result['return_msg'];
		return false;
	}
	
	/**
     * 发布订单
	*/
	public function addOrder($data = [])
	{
		$order = $this->order;
		$post_data = [
			'price_token' => $data['price_token'],//金额令牌，计算订单价格接口返回的price_token
			'order_price' => $data['total_money'],//订单金额，计算订单价格接口返回的total_money
			'balance_paymoney' => $data['need_paymoney'],//实际余额支付金额计算订单价格接口返回的need_paymoney
			'receiver' => $order['address']['name'],//收件人
			'receiver_phone' => $order['address']['phone'],//收件人电话 手机号码； 虚拟号码格式（手机号_分机号码）例如：13700000000_1111
			'note' => $order['message'],//订单备注 最长140个汉字
			'callback_url' => base_url() . $this->callback_url,//订单提交成功后及状态变化的回调地址
			'push_type' => '0',//推送方式（0 开放订单，2测试订单）默认传0即可
			'special_type' => '0',//是否需要保温箱 1需要 0不需要
			'callme_withtake' => '0',//取件是否给我打电话 1需要 0不需要
			'pubusermobile' => $order['shop']['phone'],//发件人电话，（如果为空则是用户注册的手机号）
			'pay_type' => '1' //支付方式：1=企业支付 0账户余额支付（企业余额不足自动转账户余额支付）	
		];
		!empty($order['message']) && $post_data['note'] = $order['message'];//订单备注 最长140个汉字
		$result = $this->request_post('/v2_0/addorder.ashx',$post_data);
		if($result['return_code'] == 'ok'){
			return $result;
		}
		$this->error = $result['return_msg'];
		return false;
	}

	/**
     * 取消订单
	*/
	public function cancelOrder($order_no = '')
	{
		$order = $this->order;
		$post_data = [
			//'origin_id' => '',//第三方对接平台订单id，order_code和origin_id必须二选其一
			'order_code' => $order_no,//UU跑腿订单编号，order_code和origin_id必须二选其一
			'reason' => '商家取消',//取消原因
		];
		$result = $this->request_post('/v2_0/cancelorder.ashx',$post_data);
		if($result['return_code'] == 'ok'){
			return $result;
		}
		$this->error = $result['return_msg'];
		return false;
	}	

	/**
	 * 发起http post请求
	 */
	private function request_post($url = '', $post_data = array()) 
	{
		$post_data['appid'] = $this->config['app_id'];			//应用ID
		$post_data['openid'] = $this->config['open_id'];		//商户编号
        $post_data['timestamp'] = time();			//时间戳
        $post_data['nonce_str'] = $this->guid();		//随机字符串
		$post_data['sign'] = $this->sign($post_data);//签名
		$url = $this->config['api_url'] . $url;			//拼接API接口地址
		
		$arr = [];
		foreach ($post_data as $key => $value) {
		  $arr[] = $key.'='.$value;
		}
		$curlPost = implode('&', $arr);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
		$data = curl_exec($ch);
		curl_close($ch);
		return json_decode($data,true);
	}

	// 生成guid
	private function guid()
	{
		if (function_exists('com_create_guid')){
			$uuid = com_create_guid();
		}else{
			mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
			$charid = strtoupper(md5(uniqid(rand(), true)));
			$hyphen = chr(45);// "-"
			$uuid = substr($charid, 0, 8).$hyphen
					.substr($charid, 8, 4).$hyphen
					.substr($charid,12, 4).$hyphen
					.substr($charid,16, 4).$hyphen
					.substr($charid,20,12);  
		}
		$uuid = str_replace('-', '', $uuid);
		return strtolower($uuid);
	}

	// 生成签名
	private function sign($data) 
	{
		ksort($data);//从小到大排序（字典序）
		$string = http_build_query($data);//构造URL字符串
		$string = urldecode($string);
		$string .= '&key='.$this->config['app_key'];
		$string = strtoupper($string);//字母转换为大写
		$string = md5($string);//MD5(32位)加密
		$sign = strtoupper($string);//字母转换为大写
		return $sign;
	}

	
	/**
     * 获取订单详情
	*/
	public function getorderdetail($order_id)
	{
		$post_data = [
			//'order_code' => $order_id,//UU跑腿订单编号，order_code和origin_id必须二选其一，如果都传，则只根据order_code返回
			'origin_id' => $order_id //第三方对接平台订单id，order_code和origin_id必须二选其一，如果都传，则只根据order_code返回
		];
		return $this->request_post('getorderdetail.ashx',$post_data);
	}
	
	/**
     * 获取已开通的城市列表
	*/
	public function getcitylist()
	{
		return $this->request_post('getcitylist.ashx');
	}
	
	/**
     * 获取余额详情
	*/
	public function getbalancedetail()
	{
		return $this->request_post('getbalancedetail.ashx');
	}
	
}
